<template>
	<view class="bind-content">
		<view class="logo">
			<image class="logo-img" src="../../static/logo.jpg" mode="aspectFill"></image>
		</view>

		<!-- 绑定信息 -->
		<view class="bind-info-section">

			<view class="bind-info-item">
				<text class="info-item-title">店代码</text>
				<input class="info-item-input" v-if="isShare" disabled type="text"
					placeholder-class="placeholderFontClass" placeholder="请输入店代码" v-model="shopidValue">
				<qj-fuzzy-search class="info-item-input" v-else ref="refFuzzySearch" :list="filShopList"
					placeholder="请输入店代码" @get-input-value="getInputValue" @confirm-value="confirmValue">
				</qj-fuzzy-search>
			</view>

			<view class="bind-info-item">
				<text class="info-item-title">真实姓名</text>
				<input class="info-item-input" type="text" placeholder-class="placeholderFontClass"
					placeholder="请输入您的真实姓名" v-model="realname">
			</view>

			<view class="bind-info-item">
				<text class="info-item-title">手机号</text>
				<input class="info-item-input" type="number" maxlength="11" placeholder-class="placeholderFontClass"
					placeholder="请输入手机号" v-model="phone">
			</view>

			<view class="bind-info-item">
				<text class="info-item-title">所属职位</text>
				<input class="info-item-input" type="text" @click="handleRolePopup"
					placeholder-class="placeholderFontClass" disabled readonly placeholder="请选择职位" v-model="role">
			</view>

			<!-- <view class="bind-info-item">
				<text class="info-item-title">所属部门</text>
				<input class="info-item-input" type="text" @click="handleDepartPopShow"
					placeholder-class="placeholderFontClass" disabled readonly placeholder="请选择部门" v-model="depart">
			</view> -->

			<view class="bind-info-item">
				<text class="info-item-title">邀请码</text>
				<input class="info-item-input" :disabled="isShare" type="password"
					placeholder-class="placeholderFontClass" placeholder="请输入邀请码" v-model="code">
			</view>

			<button class="submit-btn" @click.stop.prevent="onSubmit">确认注册</button>

		</view>
		<!-- 店代码popup -->
		<van-popup :show="shopidPopShow" position="bottom">
			<van-search v-model="searchValue" placeholder="请输入搜索关键词" />
			<van-picker show-toolbar :columns="shopList" @confirm="onShopidConfirm" @cancel="shopidPopShow = false" />
		</van-popup>
		<!-- 部门popup -->
		<van-popup :show="departPopShow" position="bottom">
			<van-picker show-toolbar :columns="departList" @confirm="onDepartConfirm" @cancel="departPopShow = false" />
		</van-popup>
		<!-- 职位popup -->
		<van-popup :show="rolePopShow" position="bottom">
			<van-picker show-toolbar :columns="roleNameList" @confirm="onRoleConfirm" @cancel="rolePopShow = false" />
		</van-popup>

		<user-info-modal :isUserInfoModalShow="isUserInfoModalShow" @allowGetUserInfo="allowGetUserInfo"
			@closeModal="isUserInfoModalShow = false"></user-info-modal>
	</view>

</template>

<script>
	import apiRqs from "@/api/api-request.js";
	import userInfoModal from "@/packageA/components/user-info-modal/user-info-modal.vue";
	import QjFuzzySearch from '@/packageA/components/qj-fuzzy-search/qj-fuzzy-search.vue';
	import debounce from '@/packageA/components/qj-fuzzy-search/debounce.js'; //防抖函数
	export default {
		components: {
			userInfoModal,
			QjFuzzySearch
		},
		data() {
			return {
				list: [],
				searchValue: '',
				shopid: '',
				realname: '',
				phone: '',
				role: '',
				roleId: '',
				code: '',
				departPopShow: false,
				depart: '',
				departList: ['售后部', '销售部', '客服部'],
				shopidPopShow: false,
				searchValue: '',
				shopList: ['AA001', 'AA002'],
				rolePopShow: false,
				roleNameList: [],
				roleIdList: [],
				userData: {},
				isUserInfoModalShow: false,
				userInfo: {},
				isLogin: false,
				isShare: false,
				userOpenid: '',
			}
		},
		computed: {
			shopidValue: {
				get: function() {
					return this.shopid;
				},
				set: function(val) {
					if (val) {
						this.shopid = val.toUpperCase();
					}
				},
			},
			filShopList() {
				return this.list.filter((p) => { //返回过滤后的数组
					const text = this.searchValue.trim();
					if (/^[a-zA-Z]+$/.test(text)) {
						return p.shopId.indexOf(this.searchValue) !== -1;
					} else if (/^[0-9]+$/.test(text)) {
						return p.shopId.indexOf(this.searchValue) !== -1;
					} else if (/^[\u4e00-\u9fa5]+$/.test(text)) {
						return p.shopName.indexOf(this.searchValue) !== -1;
					} else {
						return p.shopId.indexOf(this.searchValue) !== -1;
					}
				}) //filter是过滤函数去除了不包含关键字的情况
			}
		},
		onShow() {
			this.list = getApp().globalData.gacShopList;
		},
		onLoad(option) {
			this.handleIsRegistered();
			if (option) {
				this.shopidValue = option.shopid;
				this.shopid = option.shopid;
				this.code = option.code;
				this.isShare = option.isShare;
			}
			console.log('option', option);
		},
		methods: {
			// 获取到子组件输入框中输入的值
			getInputValue(e) {
				console.log('子组件输入框中输入的值', e);
				this.searchValue = e;
				this.shopid = e;
				debounce(this.getList, 500); //防抖 如果在项目中使用了uview-ui 则直接调用uview封装的防抖方法即可
			},
			// 通过子组件输入的值,发送请求,进行查询,获取列表
			getList() {
				if (this.searchValue) {
					this.$refs.refFuzzySearch.open();
				} else {
					this.$refs.refFuzzySearch.close();
				}
			},
			// 在父组件中拿到选中的值，以供父组件中的数据使用 示例{id:4,name:'北京理工大学'}
			confirmValue(e) {
				this.shopid = e.shopId;
			},
			onSubmit() {
				let {
					shopid,
					realname,
					phone,
					role,
					roleId,
					code
				} = this;
				if (shopid == '') {
					getApp().showToast("店代码不能为空");
					return false;
				} else if (realname == '') {
					getApp().showToast("真实姓名不能为空");
					return false;
				} else if (phone == '') {
					getApp().showToast("手机号不能为空");
					return false;
				} else if (role == '') {
					getApp().showToast("职位不能为空");
					return false;
				} else if (code == '') {
					getApp().showToast("邀请码不能为空");
					return false;
				} else {
					var that = this;
					let newRoleId = roleId + "";
					let openid = this.userOpenid;

					let rqs = {
						"openId": openid,
						"unionId": "0",
						"userMobile": phone,
						"platform": 4,
						"avatarUrl": "0",
						"province": "0",
						"city": "0",
						"gender": "0",
						"nickName": "0",
						"shopId": shopid,
						"realName": realname,
						"role": newRoleId,
						"department": '0',
						"invitationCode": code
					};
					console.log('注册请求rqs', rqs);
					getApp().showLoading();
					apiRqs._registeredUser(rqs).then((res) => {
						console.log('注册结果', res);
						if (res.code === 200) {
							uni.setStorageSync("registerData", rqs);
							that.submitToggle(shopid);
						} else if (res.code === 401) {
							getApp().reAuth();
						} else {
							getApp().showToast(res.msg);
						}
					}).catch((err) => {
						console.log('request err', err);
					})
				}
			},
			onDepartConfirm(value) {
				this.depart = value.detail.value;
				this.departPopShow = false;
			},
			onShopidConfirm(value) {
				this.shopid = value.detail.value;
				this.shopidPopShow = false;
			},
			onRoleConfirm(value) {
				console.log(value);
				this.role = value.detail.value;
				this.roleId = this.roleIdList[value.detail.index];
				this.rolePopShow = false;
			},
			// 控制部门弹出层
			handleDepartPopShow() {
				this.departPopShow = true;
			},
			// 控制店代码弹出层
			handleShopidPopup() {
				this.shopidPopShow = true;
			},
			// 控制职位弹出层
			async handleRolePopup() {
				var that = this;
				if (this.shopid == "") {
					getApp().showToast("请先输入店代码");
				} else {
					getApp().showLoading();
					await apiRqs._getRoleList(this.shopid).then((res) => {
						uni.hideLoading();
						console.log('职位列表', res);
						let roleNameList = [];
						let roleIdList = [];
						that.rolePopShow = true;
						for (let i = 0; i < res.data.length; i++) {
							roleNameList.push(res.data[i].roleName);
							roleIdList.push(res.data[i].id);
						}
						that.roleNameList = roleNameList;
						that.roleIdList = roleIdList;
					}).catch((err) => {
						console.log('request err', err);
					})
				}
			},
			allowGetUserInfo() {
				const userinfo = uni.getStorageSync("userInfo");
				this.userInfo = userinfo;
				this.isUserInfoModalShow = false;
				apiRqs._syncWechatInfo({
					AvatarUrl: userinfo.avatarUrl,
					Province: userinfo.province,
					City: userinfo.city,
					Gender: userinfo.gender,
					NickName: userinfo.nickName,
				}).then((res) => {
					console.log('同步信息', res);
				}).catch((err) => {
					console.log('err', err)
				})
			},
			// 验证是否注册
			handleIsRegistered() {
				var that = this;
				getApp().showLoading();
				uni.login({
					provider: "weixin",
					success(loginRes) {
						console.log(loginRes);
						let code = loginRes.code;
						uni.request({
							url: "https://bydapi.vaubang.cn/api/v1/WxOpen/FindOpenId?code=" +
								code,
							method: "post",
							header: {
								"content-type": "application/json;charset=utf-8;"
							},
							success(res) {
								uni.hideLoading();
								console.log('登陆信息', res);
								// 当登录者已经绑定了openid时，直接保存登录信息返回的token以及公司信息
								if (res.data.code == 200) {
									uni.setStorageSync("isLogin", true);
									uni.setStorageSync('userOpenid', res.data.data.openid);
									getApp().globalData.userOpenid = res.data.data.openid;
									that.isLogin = true;
									that.userOpenid = res.data.data.openid;
								}
							},
							fail(err) {
								console.log(err);
							}
						})
					}
				})
			},
			submitToggle(shopid) {
				var that = this;
				uni.login({
					provider: "weixin",
					success(loginRes) {
						console.log(loginRes);
						let code = loginRes.code;
						let rqs = {
							"code": code,
							"shopId": shopid
						}
						apiRqs._toggleShop(rqs).then((res) => {
							console.log('注册后默认切换到注册门店', res);
							uni.setStorageSync("loginInfo", res.data);
							uni.hideLoading();
							if (res.code == 200) {
								uni.showToast({
									title: '注册成功',
									icon: 'success',
									success() {
										uni.reLaunch({
											url: "/pages/workbench/workbench"
										})
									}
								})
							} else {
								getApp().showToast(res.msg);
							}
						}).catch((err) => {
							console.log('err', err);
						})
					}
				})
			},
		}
	}
</script>

<style lang="less">
	.bind-content {
		.logo {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 50px;

			.logo-img {
				width: 70px;
				height: 70px;
				border-radius: 50%;
			}
		}

		.bind-info-section {
			margin: 50px 20px 0px 20px;

			.bind-info-item {
				display: flex;
				align-items: center;
				width: 100%;
				height: 54px;
				line-height: 54px;
				padding: 0 20px;
				box-sizing: border-box;
				border-bottom: 1px solid #f5f5f5;

				&:first-child {
					border-top: 1px solid #f5f5f5;
				}

				.info-item-title {
					width: 80px;
					flex: 0 0 80px;
					font-size: 14px;
					color: rgba(0, 0, 0, 0.7);
				}

				.info-item-input {
					flex: 1;
					font-size: 14px;
					text-align: left;
					color: #666666;
				}

				.placeholderFontClass {
					color: #ddd;
				}
			}

			.submit-btn {
				margin-top: 20px;
				border: none;
				background-color: #008aff;
				color: #fff;
				font-size: 14px;
				height: 35pt;
				line-height: 35pt;

				&:active {
					background-color: #0076DB;
				}
			}
		}
	}
</style>